package grimbo.goodwinfooty.processing;

import grimbo.goodwinfooty.xls.XLS2CSVmra;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Map;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class XLS2CSVmraProcessor implements Processor {
	public final static String CTX_CSV_BYTES = "csvBytes";

	public String process(Map context) throws Exception {
		InputStream in = (InputStream) context
				.get(XLS2InputStreamProcessor.CTX_XLS_INPUT_STREAM);
		byte[] csvBytes = convertXLS2CSV(in);
		context.put(CTX_CSV_BYTES, csvBytes);
		return null;
	}

	private byte[] convertXLS2CSV(InputStream in) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(baos);

		POIFSFileSystem fs = new POIFSFileSystem(in);
		XLS2CSVmra xls2csv = new XLS2CSVmra(fs, ps, -1);
		xls2csv.process();
		ps.flush();
		return baos.toByteArray();
	}
}
